package com.leyou.trade.service.impl;

import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository repository;

    @Override
    public void addCart(CartItem cartItem) {

        String id = buildId(cartItem.getSkuId());

        Optional<CartItem> optional = repository.findById(id);

        //如果加入过合并数量
        if (optional.isPresent()) {
            CartItem item = optional.get();
            cartItem.setNum(cartItem.getNum() + item.getNum());
        } else {
            cartItem.setId(id);

            cartItem.setUserId(UserContext.getUser().getId());
        }


        repository.save(cartItem);

    }

    @Override
    public String buildId(Long skuId) {

        // %d站位，整数，%f，浮点数，%s，字符串
        return String.format("U%dS%d", UserContext.getUser().getId(), skuId);

    }

    @Override
    public List<CartItem> listUserCarts() {

        List<CartItem> cartItems = this.repository.findByUserId(UserContext.getUser().getId());


        return cartItems;
    }
}
